package com.txby.wrApi.component.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
	HttpServletRequest orgRequest = null;
	public XssAndSqlHttpServletRequestWrapper(HttpServletRequest servletRequest) {
		super(servletRequest);
		this.orgRequest=servletRequest;
	}
 	 @Override
	public String[] getParameterValues(String parameter) {
		String[] values = super.getParameterValues(parameter);
		if (values == null) {
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = cleanXSS(values[i]);
		}
		return encodedValues;
	} 

	@Override
	public String getParameter(String parameter) {
		String value = super.getParameter(parameter);
		if (value == null) {
			return null;
		}
		return cleanXSS(value);
	}

/*	@Override
	public String getHeader(String name) {
		String value = super.getHeader(name);
		if (value == null)
			return null;
		return cleanXSS(value);
	}*/

	/*@Override
	@SuppressWarnings("all")
	public Map getParameterMap() {
		Map  paramMap = super.getParameterMap();
		Map  map = new HashMap();
		Set<String> keySet = paramMap.keySet();
		if (paramMap != null) {
			try {
				for (Object ent: keySet.toArray()) {
					String  key=ent.toString();
					String  val=((String[])paramMap.get(ent))[0];
							val = HtmlUtils.htmlEscape(val);
							val=JavaScriptUtils.javaScriptEscape(val);
							map.put(ent,val);
				}
			} catch (Exception e) {
				System.out.println("字符过滤时出现异常，错误原因：" + e.getMessage());
			}
		}
		
		return map;
	}*/

	private String cleanXSS(String value) {
//		System.out.println("dd:"+value);
		/*String flt = "'|and|exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare|;|or|grant|drop|&";
		String filter[] = flt.split("\\|");
		value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
		value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
		value = value.replaceAll("'", "& #39;");
		value = value.replaceAll("eval\\((.*)\\)", "");
		value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
				"\"\"");
		value = value.replaceAll("script", "");
		for (int i = 0; i < filter.length; i++) {
			value = value.replaceAll(filter[i], "");
		}*/
//		value=HtmlUtils.htmlEscape(value);
//		value=JavaScriptUtils.javaScriptEscape(value);
		return value;
	}
	
	/**
	* 获取最原始的request
	* @return  HttpServletRequest
	*/
	public HttpServletRequest getOrgRequest() {
		return orgRequest;
	}
	/**
	 * 获取最原始的request的静态方法
	 * @param req
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if (req instanceof XssAndSqlHttpServletRequestWrapper) {
			return ((XssAndSqlHttpServletRequestWrapper) req).getOrgRequest();
		}

		return req;
	}

}